// LAMEFile.cpp: implementation of the LAMEFile class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "LAMEFile.h"
#include "LString.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LAMEFile::LAMEFile()
{
  fileHandle = INVALID_HANDLE_VALUE;
  isOpen=false;
}

LAMEFile::~LAMEFile()
{

}


bool LAMEFile::open(const TCHAR *filename, eFileMode mode)
{
  //for easier access if we want to expand the path.. 
  String temp=filename;
  //temp=getRelativePath(temp);      

  //it's time to open the file 
  fileHandle = CreateFile(temp, 
    mode==FILE_READ ? GENERIC_READ : GENERIC_WRITE, NULL, NULL,
    mode==FILE_READ ? OPEN_EXISTING : CREATE_ALWAYS,
    FILE_ATTRIBUTE_NORMAL, NULL);
  
  if (fileHandle == INVALID_HANDLE_VALUE) 
    isOpen=false;
  else
    isOpen=true;

  return isOpen;
}


void LAMEFile::close()
{
  if (isOpen)
  {
    //close the file and reset variables
    CloseHandle(fileHandle); 
    fileHandle=INVALID_HANDLE_VALUE;
    isOpen=false;
  }
}

int LAMEFile::fileSize()
{
  if (!isOpen) //of course
    return 0;
  else
    return GetFileSize(fileHandle,0);
}

int LAMEFile::write(void *data, int size) //let's do some writing
{
  if (isOpen)
  {
    DWORD written;
    WriteFile(fileHandle, data, size, &written,0);
    return written; //we return the number of bytes that actually got written
  }
  else
  {
    return 0;
  }
}

int LAMEFile::read(void *data, int size) 
{
  if (isOpen)
  {
    DWORD wasRead;
    ReadFile(fileHandle, data, size, &wasRead,0);
    return wasRead; //we return the number of bytes that actually was read
  }
  else
  {
    return 0;
  }
}


int LAMEFile::readInt()
{
  int temp;
  if (read(&temp, sizeof(int)))
    return temp;
  else
    return 0;
}

void LAMEFile::writeInt(int i)
{
  write(&i,sizeof(int));
}

char LAMEFile::readChar()
{
  char temp;
  if (read(&temp, sizeof(char)))
    return temp;
  else
    return 0;
}

void LAMEFile::writeChar(char i)
{
  write(&i,sizeof(char));
}